package com.fh.controller.dog.admin;

import com.fh.controller.base.BaseController;
import com.fh.entity.Page;
import com.fh.entity.system.Role;
import com.fh.entity.system.User;
import com.fh.service.system.fhlog.FHlogManager;
import com.fh.service.system.role.RoleManager;
import com.fh.service.system.user.UserManager;
import com.fh.util.*;
import com.fh.util.layui.DataUtil;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 类名称：UserController
 *
 * @version 1.0
 * @author：Lr 更新时间：2017年12月21日
 */
@Controller
@RequestMapping(value = "/yshUser")
public class YshUserController extends BaseController {

    /**
     * 菜单地址(权限用)
     */
    private String menuUrl = "user/list.do";
    @Resource(name = "userService")
    private UserManager userService;
    @Resource(name = "roleService")
    private RoleManager roleService;
    @Resource(name = "fhlogService")
    private FHlogManager FHLOG;

    /**
     * 显示用户列表
     *
     * @param page
     * @return String
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public String list(Page page) throws Exception {
        PageData pd = this.getPageData();
        String data = "";
        try {
            //关键词检索条件
            String keywords = pd.getString("keywords");
            if (null != keywords && !"".equals(keywords)) {
                pd.put("keywords", keywords.trim());
            }
            //开始时间
            String lastLoginStart = pd.getString("lastLoginStart");
            //结束时间
            String lastLoginEnd = pd.getString("lastLoginEnd");
            if (lastLoginStart != null && !"".equals(lastLoginStart)) {
                pd.put("lastLoginStart", lastLoginStart + " 00:00:00");
            }
            if (lastLoginEnd != null && !"".equals(lastLoginEnd)) {
                pd.put("lastLoginEnd", lastLoginEnd + " 00:00:00");
            }
            page.setPd(pd);
            DataUtil.setPage(page, pd);
            List<PageData> list = userService.listUsers(page);
            data = DataUtil.getJsonData(page, list);
        } catch (Exception e) {
            logger.error(e.toString(), e);
        } finally {
            logAfter(logger);
        }
        return data;
    }

    /**
     * 保存用户
     *
     * @param
     * @return PageData
     * @throws Exception
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public PageData save() throws Exception {
        //校验权限
        String type = "add";
        if (!Jurisdiction.buttonJurisdiction(menuUrl, type)) {
            return null;
        }
    //    logBefore(logger, Jurisdiction.getUsername() + "新增user");
        PageData result = new PageData();
        PageData pd = this.getPageData();
        //ID 主键
        pd.put("USER_ID", this.get32UUID());
        //角色
        pd.put("ROLE_ID", "2");
        //最后登录时间
        pd.put("LAST_LOGIN", "");
        //IP
        pd.put("IP", "");
        //状态
        pd.put("STATUS", "0");
        pd.put("SKIN", "default");
        pd.put("RIGHTS", "");
        //密码加密
        pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
        try {
            //判断用户名是否存在
            if (null == userService.findByUsername(pd)) {
                //执行保存
                userService.saveU(pd);
                result.put("data", "");
                result.put("returnCode", "00");
                result.put("returnMsg", "新增用户成功");
                FHLOG.save(Jurisdiction.getUsername(), "新增系统用户：" + pd.getString("USERNAME"));
            } else {
                result.put("data", "");
                result.put("returnCode", "11");
                result.put("returnMsg", "用户已存在");
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
            result.put("data", "");
            result.put("returnCode", "01");
            result.put("returnMsg", "新增用户失败");
            FHLOG.save(Jurisdiction.getUsername(), "新增系统用户失败：" + pd.getString("USERNAME"));
        }
        return result;
    }

    /**
     * 查看用户
     *
     * @param
     * @return PageData
     * @throws Exception
     */
    @RequestMapping(value = "/view")
    @ResponseBody
    public PageData view() throws Exception {
        //校验权限
        String type = "cha";
        if (!Jurisdiction.buttonJurisdiction(menuUrl, type)) {
            return null;
        }
        PageData result = new PageData();
        PageData pd = this.getPageData();
        //不能查看admin用户
        if ("admin".equals(pd.getString("USERNAME"))) {
            return null;
        }
        pd.put("ROLE_ID", "1");
        try {
            //列出所有系统用户角色
            List<Role> roleList = roleService.listAllRolesByPId(pd);
            //根据ID读取
            pd = userService.findById(pd);
            result.put("data", pd);
            result.put("roleList", roleList);
            result.put("returnCode", "00");
            result.put("returnMsg", "查看用户成功");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            result.put("data", "");
            result.put("returnCode", "01");
            result.put("returnMsg", "查看用户失败");
        }
        return result;
    }

    /**
     * 查看个人信息
     *
     * @param
     * @return PageData
     * @throws Exception
     */
    @RequestMapping(value = "/info")
    @ResponseBody
    public PageData info() throws Exception {
        PageData result = new PageData();
        PageData pd = this.getPageData();
        try {
            User user = SessionUtil.getSessionUser();
            pd.put("USER_ID", user.getUSER_ID());
            pd.put("USERNAME", user.getUSERNAME());
            pd.put("NAME", user.getNAME());
            result.put("data", pd);
            result.put("returnCode", "00");
            result.put("returnMsg", "查看个人信息成功");
        } catch (Exception e) {
            logger.error(e.toString(), e);
            result.put("data", "");
            result.put("returnCode", "01");
            result.put("returnMsg", "查看个人信息失败");
        }
        return result;
    }

    /**
     * 修改用户
     *
     * @param
     * @return PageData
     * @throws Exception
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public PageData edit() throws Exception {
        logBefore(logger, Jurisdiction.getUsername() + "修改ser");
        PageData result = new PageData();
        PageData pd = this.getPageData();
        //如果当前登录用户修改用户资料提交的用户名非本人
        if (!Jurisdiction.getUsername().equals(pd.getString("USERNAME"))) {
            //校验权限 判断当前操作者有无用户管理查看权限
            if (!Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
                return null;
            }
            //校验权限判断当前操作者有无用户管理修改权限
            if (!Jurisdiction.buttonJurisdiction(menuUrl, "edit")) {
                return null;
            }
            //非admin用户不能修改admin
            if ("admin".equals(pd.getString("USERNAME")) && !"admin".equals(Jurisdiction.getUsername())) {
                return null;
            }
        } else {
            //如果当前登录用户修改用户资料提交的用户名是本人，则不能修改本人的角色ID
            //对角色ID还原本人角色ID
            pd.put("ROLE_ID", userService.findByUsername(pd).getString("ROLE_ID"));
            //对角色ID还原本人副职角色ID
            pd.put("ROLE_IDS", userService.findByUsername(pd).getString("ROLE_IDS"));
        }
        if (pd.getString("PASSWORD") != null && !"".equals(pd.getString("PASSWORD"))) {
            pd.put("PASSWORD", new SimpleHash("SHA-1", pd.getString("USERNAME"), pd.getString("PASSWORD")).toString());
        }
        try {
            //执行修改
            userService.editU(pd);
            result.put("data", "");
            result.put("returnCode", "00");
            result.put("returnMsg", "修改用户成功");
            FHLOG.save(Jurisdiction.getUsername(), "修改系统用户：" + pd.getString("USERNAME"));
        } catch (Exception e) {
            logger.error(e.toString(), e);
            result.put("data", "");
            result.put("returnCode", "01");
            result.put("returnMsg", "修改用户失败");
            FHLOG.save(Jurisdiction.getUsername(), "修改系统用户失败：" + pd);
        }
        return result;
    }

    /**
     * 删除用户
     *
     * @param
     * @return PageData
     * @throws Exception
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public PageData delete() throws Exception {
        //校验权限
        String type = "del";
        if (!Jurisdiction.buttonJurisdiction(menuUrl, type)) {
            return null;
        }
        logBefore(logger, Jurisdiction.getUsername() + "删除user");
        PageData result = new PageData();
        PageData pd = this.getPageData();
        try {
            userService.deleteU(pd);
            result.put("data", "");
            result.put("returnCode", "00");
            result.put("returnMsg", "删除用户成功");
            FHLOG.save(Jurisdiction.getUsername(), "删除系统用户：" + pd);
        } catch (Exception e) {
            logger.error(e.toString(), e);
            result.put("data", "");
            result.put("returnCode", "01");
            result.put("returnMsg", "删除用户失败");
            FHLOG.save(Jurisdiction.getUsername(), "删除系统用户失败：" + pd);
        }
        return result;
    }



    /**
     * 导出用户信息到EXCEL
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/excel")
    public ModelAndView exportExcel() throws Exception {
        FHLOG.save(Jurisdiction.getUsername(), "导出用户信息到EXCEL");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        pd = this.getPageData();
        try {
            if (Jurisdiction.buttonJurisdiction(menuUrl, "cha")) {
                String keywords = pd.getString("keywords");                //关键词检索条件
                if (null != keywords && !"".equals(keywords)) {
                    pd.put("keywords", keywords.trim());
                }
                String lastLoginStart = pd.getString("lastLoginStart");    //开始时间
                String lastLoginEnd = pd.getString("lastLoginEnd");        //结束时间
                if (lastLoginStart != null && !"".equals(lastLoginStart)) {
                    pd.put("lastLoginStart", lastLoginStart + " 00:00:00");
                }
                if (lastLoginEnd != null && !"".equals(lastLoginEnd)) {
                    pd.put("lastLoginEnd", lastLoginEnd + " 00:00:00");
                }
                Map<String, Object> dataMap = new HashMap<String, Object>();
                List<String> titles = new ArrayList<String>();
                titles.add("用户名");        //1
                titles.add("编号");        //2
                titles.add("姓名");            //3
                titles.add("职位");            //4
                titles.add("手机");            //5
                titles.add("邮箱");            //6
                titles.add("最近登录");        //7
                titles.add("上次登录IP");    //8
                dataMap.put("titles", titles);
                List<PageData> userList = userService.listAllUser(pd);
                List<PageData> varList = new ArrayList<PageData>();
                for (int i = 0; i < userList.size(); i++) {
                    PageData vpd = new PageData();
                    vpd.put("var1", userList.get(i).getString("USERNAME"));        //1
                    vpd.put("var2", userList.get(i).getString("NUMBER"));        //2
                    vpd.put("var3", userList.get(i).getString("NAME"));            //3
                    vpd.put("var4", userList.get(i).getString("ROLE_NAME"));    //4
                    vpd.put("var5", userList.get(i).getString("PHONE"));        //5
                    vpd.put("var6", userList.get(i).getString("EMAIL"));        //6
                    vpd.put("var7", userList.get(i).getString("LAST_LOGIN"));    //7
                    vpd.put("var8", userList.get(i).getString("IP"));            //8
                    varList.add(vpd);
                }
                dataMap.put("varList", varList);
                ObjectExcelView erv = new ObjectExcelView();                    //执行excel操作
                mv = new ModelAndView(erv, dataMap);
            }
        } catch (Exception e) {
            logger.error(e.toString(), e);
        }
        return mv;
    }

    /**
     * 打开上传EXCEL页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/goUploadExcel")
    public ModelAndView goUploadExcel() throws Exception {
        ModelAndView mv = this.getModelAndView();
        mv.setViewName("system/user/uploadexcel");
        return mv;
    }

    /**
     * 下载模版
     *
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/downExcel")
    public void downExcel(HttpServletResponse response) throws Exception {
        FileDownload.fileDownload(response, PathUtil.getClasspath() + Const.FILEPATHFILE + "Users.xls", "Users.xls");
    }

    /**
     * 从EXCEL导入到数据库
     *
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/readExcel")
    public ModelAndView readExcel(
            @RequestParam(value = "excel", required = false) MultipartFile file
    ) throws Exception {
        FHLOG.save(Jurisdiction.getUsername(), "从EXCEL导入到数据库");
        ModelAndView mv = this.getModelAndView();
        PageData pd = new PageData();
        if (!Jurisdiction.buttonJurisdiction(menuUrl, "add")) {
            return null;
        }
        if (null != file && !file.isEmpty()) {
            String filePath = PathUtil.getClasspath() + Const.FILEPATHFILE;                                //文件上传路径
            String fileName = FileUpload.fileUp(file, filePath, "userexcel");                            //执行上传
            List<PageData> listPd = (List) ObjectExcelRead.readExcel(filePath, fileName, 2, 0, 0);        //执行读EXCEL操作,读出的数据导入List 2:从第3行开始；0:从第A列开始；0:第0个sheet
            /*存入数据库操作======================================*/
            pd.put("RIGHTS", "");                    //权限
            pd.put("LAST_LOGIN", "");                //最后登录时间
            pd.put("IP", "");                        //IP
            pd.put("STATUS", "0");                    //状态
            pd.put("SKIN", "default");                //默认皮肤
            pd.put("ROLE_ID", "1");
            List<Role> roleList = roleService.listAllRolesByPId(pd);//列出所有系统用户角色
            pd.put("ROLE_ID", roleList.get(0).getROLE_ID());        //设置角色ID为随便第一个
            /**
             * var0 :编号
             * var1 :姓名
             * var2 :手机
             * var3 :邮箱
             * var4 :备注
             */
            for (int i = 0; i < listPd.size(); i++) {
                pd.put("USER_ID", this.get32UUID());                                        //ID
                pd.put("NAME", listPd.get(i).getString("var1"));                            //姓名

                String USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1"));    //根据姓名汉字生成全拼
                pd.put("USERNAME", USERNAME);
                if (userService.findByUsername(pd) != null) {                                    //判断用户名是否重复
                    USERNAME = GetPinyin.getPingYin(listPd.get(i).getString("var1")) + Tools.getRandomNum();
                    pd.put("USERNAME", USERNAME);
                }
                pd.put("BZ", listPd.get(i).getString("var4"));                                //备注
                if (Tools.checkEmail(listPd.get(i).getString("var3"))) {                        //邮箱格式不对就跳过
                    pd.put("EMAIL", listPd.get(i).getString("var3"));
                    if (userService.findByUE(pd) != null) {                                    //邮箱已存在就跳过
                        continue;
                    }
                } else {
                    continue;
                }
                pd.put("NUMBER", listPd.get(i).getString("var0"));                            //编号已存在就跳过
                pd.put("PHONE", listPd.get(i).getString("var2"));                            //手机号

                pd.put("PASSWORD", new SimpleHash("SHA-1", USERNAME, "123").toString());    //默认密码123
                if (userService.findByUN(pd) != null) {
                    continue;
                }
                userService.saveU(pd);
            }
            /*存入数据库操作======================================*/
            mv.addObject("msg", "success");
        }
        mv.setViewName("save_result");
        return mv;
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(format, true));
    }

}
